package cn.edu.sdjzu.xg.bysj.controller.basic;

import cn.edu.sdjzu.xg.bysj.domain.GraduateProject;
import cn.edu.sdjzu.xg.bysj.service.GraduateProjectService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;

@WebServlet("/graduateProject.ctl")
public class GraduateProjectController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //设置响应字符编码为UTF-8
        response.setContentType("application/json;charset=UTF-8");
        //读取参数id
        String id_str = request.getParameter("id");

        try {
            //如果id = null, 表示响应所有学位对象，否则响应id指定的学位对象
            if (id_str == null) {
                this.responseGraduateProjects(response);
            } else {
                //根据id查找某个学位
                int id = Integer.parseInt(id_str);
                responseGraduateProject(id, response);
            }
        }catch (SQLException e){
            //响应message到前端
            response.getWriter().println("Exception occurs!"+e.getMessage());
        }catch(Exception e){
            //响应message到前端
            response.getWriter().println("Exception occurs!"+e.getMessage());
        }
    }
    //响应一个学位对象
    private void responseGraduateProject(int id, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        //根据id查找学位
        GraduateProject graduateProject = GraduateProjectService.getInstance().find(id);
        String graduateProject_json = JSON.toJSONString(graduateProject);

        //响应degree_json到前端
        response.getWriter().println(graduateProject_json);
    }
    //响应所有学位对象
    private void responseGraduateProjects(HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        //获得所有学位
        Collection<GraduateProject> graduateProjects = GraduateProjectService.getInstance().findAll();
        String graduateProjects_json = JSON.toJSONString(graduateProjects, SerializerFeature.DisableCircularReferenceDetect);

        //响应degrees_json到前端
        response.getWriter().println(graduateProjects_json);
    }
}
